package com.captjack.rest.configuration.security;

import com.captjack.rest.filter.LoginTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.context.NullSecurityContextRepository;

/**
 * rest访问权限设置
 *
 * @author Jack Sparrow
 * @version 1.0.0
 * @date 2018/6/3 11:19
 * package com.captjack.rest.configuration
 */
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    /**
     *
     */
    private final LoginTokenFilter loginTokenFilter;

    /**
     * 在此配置不过滤的请求
     */
    @Override
    public void configure(WebSecurity web) {
        // 每一个请求对应一个空的filter链,这里一般不要配置过多,
        // 因为查找处是一个for循环,过多就导致每个请求都需要循环一遍直到找到
        web.ignoring().antMatchers("/", "/api/login", "/favicon.ico");
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .authorizeRequests()
                // 角色定义,Spring Security会在其前面自动加上ROLE_,因此存储权限的时候也要加上ROLE_ADMIN
                .anyRequest().permitAll().and()
                // 异常处理,可以再此使用entrypoint来定义错误输出
                .exceptionHandling().and()
                // 不需要session来控制,所以这里可以去掉
                .securityContext().securityContextRepository(new NullSecurityContextRepository()).and()
                // 开启匿名访问
                .anonymous().and()
                // 退出登录自己来控制
                .logout().disable()
                // 因为没用到cookies,所以关闭cookies
                .csrf().disable()
                // 验证token
                .addFilterBefore(loginTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Autowired
    public SecurityConfiguration(LoginTokenFilter loginTokenFilter) {
        this.loginTokenFilter = loginTokenFilter;
    }

}
